package com.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oracle.mapper.AdminMapper;
import com.oracle.pojo.Admin;
import com.oracle.pojo.LoginForm;
import com.oracle.service.IAdminService;
import com.oracle.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("adminServiceImpl")   // 指定当前实现类的id
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Override
    public Admin login(LoginForm loginForm) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        // 使用adminQueryWrapper设定查询语句的筛选条件，相当于where后面的语句
        // tb_admin数据表中的name字段和登录页面对象中的username属性匹配
        adminQueryWrapper.eq("name",loginForm.getUsername());
        // tb_admin数据表中的通过MD5加密后的password字段和登录页面对象中的password属性匹配
        // 这里的第二个参数需要使用MD5加密，因为数据库中的password字段存储的是通过MD5加密后的值
        adminQueryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        // 使用MybatisPlus的内置baseMapper调用查询单个方法，查询数据库的Admin对象
        Admin admin = baseMapper.selectOne(adminQueryWrapper);
        // 方法返回Admin对象
        return admin;
    }

    @Override
    public Admin getAdminById(Long userId) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("id",userId);
        Admin admin = baseMapper.selectOne(adminQueryWrapper);
        return admin;
    }

    @Override
    public IPage<Admin> getAdminsByConditions(Page<Admin> adminPage, String adminName) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(adminName)) {
            adminQueryWrapper.like("name",adminName);
        }
        adminQueryWrapper.orderByDesc("id");
        Page<Admin> page = baseMapper.selectPage(adminPage, adminQueryWrapper);
        return page;
    }
}
